package com.xpgk.mvc.btoShop;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Record;
import com.sun.java_cup.internal.runtime.virtual_parse_stack;
import com.sun.org.apache.bcel.internal.generic.Select;
import com.xpgk.annotation.Service;
import com.xpgk.constant.ConstantRender;
import com.xpgk.mvc.base.BaseService;
import com.xpgk.mvc.bentryRegister.Customer;
import com.xpgk.mvc.bentryRegister.CustomerDetail;
import com.xpgk.mvc.bentryRegister.CustomerProduct;
import com.xpgk.mvc.binShopService.CustomerService;
import com.xpgk.mvc.intoPersonnel.IntoPersonnel;
import com.xpgk.mvc.organization.Organization;
import com.xpgk.mvc.productSales.ProductSales;
import com.xpgk.mvc.productSales.ProductSalesOrder;
import com.xpgk.mvc.productSet.Product;
import com.xpgk.mvc.statistic.dailyTotalStatistic.DailyNursingTotal;
import com.xpgk.tools.ToolDateTime;


@Service(name = BintoShopService.serviceName)
public class BintoShopService extends  BaseService{
	
	
	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(BintoShopService.class);
	public static final String serviceName = "bintoShopService";
	
	
	
	public  List<Record>  getIntoShop(String organIds)
	{
		 Map<String, Object> queryParam = new HashMap<String, Object>();
		 queryParam.put("intoShopIds", organIds);
		 List<Record> lis = find(BtoShop.sqlId_getIntoShops, queryParam);
		 if(lis!=null && lis.size()>0)
		 {
			 return  lis;
		 }else
		 {
			 return  null;
		 }
	}
	
	public List<Record>  searchCus(String organIds,String outShopIds)
	{
		Map<String, Object> queryParam = new HashMap<String, Object>();
		 queryParam.put("intoShopIds", organIds);
		
		 queryParam.put("outShopIds", outShopIds);
		 List<Record> lis = find(BtoShop.sqlId_getIntoShops, queryParam);
		 return lis;
	}
	
	
	
	public  String  saveIntoShop(String customerIds,List<ProductSales>  cpsList,String organIds,String userIds,String outorganIds )
	{	
		BtoShop  bs=BtoShop.dao.getIntoShop(customerIds, organIds);
		if(bs!=null)
		{
			bs.set(BtoShop.column_isConfirm, "1")
				.set(BtoShop.column_confirmUserIds, userIds)
				.set(BtoShop.column_intoTime, new Date())
				.set(BtoShop.column_gxsj, new Date());
			if(!bs.update())
			{
				log.debug("更新转店记录失败");
				throw new RuntimeException("更新转店记录失败!");
			}
		}
		//更新顾客信息
		String chybh="000001";
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("column", Customer.column_organIds);
		String sql = getSqlByBeetl(Customer.sqlId_column, param);
		List<Customer>  clist=Customer.dao.find(sql,organIds);
		ArrayList<Integer>  numList=new ArrayList<Integer>();
		if(clist!=null  && clist.size()>0)
		{
			for(Customer cuss:clist)
			{	
				String hybh=cuss.getStr(Customer.column_hybh);
				int n=Integer.parseInt(hybh);
				numList.add(n);
			}
			int a=Collections.max(numList);
			chybh=String.format("%06d", a+1);
		}
		Customer cs=Customer.dao.findById(customerIds);
		cs.set(Customer.column_organIds, organIds)
			.set(Customer.column_hybh, chybh)
			.set(Customer.column_dataStatus, "1");
		if(!cs.update())
		{
			log.debug("更新顾客信息失败");
			throw new RuntimeException("更新顾客信息失败!");
		}
		//更新顾客详情
		
		/*Map<String, Object> param1 = new HashMap<String, Object>();
		param1.put("column",CustomerDetail.column_customerIds); 
		String sqlPara = getSqlByBeetl(CustomerDetail.sqlId_column, param1);*/
		String sql2 = "select * FROM sb_customer_detail WHERE customerIds = ? ";
		//IntoPersonnel personnel = IntoPersonnel.dao.findFirst(sql, intoPersonnel.getStr(IntoPersonnel.column_userIds));
		CustomerDetail customerDetail = CustomerDetail.dao.findFirst(sql2,customerIds);
		Organization org = Organization.dao.findById(organIds);
		if(customerDetail!=null){
			customerDetail.set(CustomerDetail.column_organIds, organIds)
			.set(CustomerDetail.column_organName, org.getStr(Organization.column_name))
			.set(CustomerDetail.column_hybh, chybh)
			.set(CustomerDetail.column_chargePersion, org.getStr(Organization.column_agentIds))
			.set(CustomerDetail.column_dataStatus, "1");
			if( customerDetail.getFloat(CustomerDetail.column_nowWeight)!=null){
				customerDetail.set(CustomerDetail.column_firstWeight, customerDetail.getFloat(CustomerDetail.column_nowWeight))
				.set(CustomerDetail.column_delWeight, customerDetail.getFloat(CustomerDetail.column_nowWeight)- customerDetail.getFloat(CustomerDetail.column_targetWeight));
			}
			if( ToolDateTime.format(customerDetail.getDate(CustomerDetail.column_firstDate), ToolDateTime.pattern_y).equals(ToolDateTime.format(new Date(), ToolDateTime.pattern_y))){
				customerDetail.set(CustomerDetail.column_firstDate, new Date());
			}
			if(!customerDetail.update()){
				log.debug("更新顾客详细信息失败");
				throw new RuntimeException("更新顾客详细信息失败!");
			}
		}
		//更新顾客产品
		List<CustomerProduct>  cusproList=CustomerProduct.dao.getCustomerProduct(customerIds, bs.getStr(BtoShop.column_outShopIds));
		if(cusproList!=null  && cusproList.size()>0)
		{
			for(CustomerProduct  cp:cusproList)
			{
				cp.set(CustomerProduct.column_organids, organIds)
					.set(CustomerProduct.column_updateDate, new Date());
				if(!cp.update())
				{
					log.debug("更新顾客产品信息失败");
					throw new RuntimeException("更新顾客产品信息失败!");
				}
			}
		}
		
		//保存销售订单
		float price = 0f;
		for(ProductSales  pss:cpsList){
			
				price  = price+pss.getFloat(ProductSales.column_price);
			
			
		}
		ProductSalesOrder productSalesOrder = new ProductSalesOrder();
		productSalesOrder.set(ProductSalesOrder.column_organIds, organIds)
		.set(ProductSalesOrder.column_customerIds, outorganIds)
		.set(ProductSalesOrder.column_orderNumber, "zd")
		.set(ProductSalesOrder.column_userIds, userIds)
		.set(ProductSalesOrder.column_receivable, price)
		.set(ProductSalesOrder.column_proceeds, price)
		.set(ProductSalesOrder.column_arrears, 0.0)
		.set(ProductSalesOrder.column_dataStatus,"3")
		.set(ProductSalesOrder.column_date, new Date())
		.set(ProductSalesOrder.column_createDate, new Date());
		
		if(!productSalesOrder.save()){
			log.debug("订单保存失败");
			throw new RuntimeException("订单保存失败!");
		}else{
			for(ProductSales  pss:cpsList){
				float totalPrice = pss.getFloat(ProductSales.column_price);
				int num = pss.getInt(ProductSales.column_number);
				float unit = totalPrice/num;
				Product product = Product.dao.findById(pss.getStr(ProductSales.column_productID));
				pss.set(ProductSales.column_orderIds, productSalesOrder.getStr(ProductSalesOrder.column_ids))
				.set(ProductSales.column_organids, organIds)
				.set(ProductSales.column_type, product.getStr(Product.column_typeIds))
				.set(ProductSales.column_customerID, outorganIds)
				.set(ProductSales.column_userID, userIds)
				.set(ProductSales.column_createId, userIds)
				.set(ProductSales.column_unitPrice, unit)
				.set(ProductSales.column_consumerType, "5")
				.set(ProductSales.column_dataStatus, "3")
				.set(ProductSales.column_bz, "顾客转店")
				.set(ProductSales.column_date, new Date())
				.set(ProductSales.column_createDate, new Date());
				
				if(!pss.save()){
					log.debug("订单详细保存失败");
					throw new RuntimeException("订单详细保存失败!");
				}
			}
		}
		
		//保存日销售综合表
		DailyNursingTotal  dnt = DailyNursingTotal.dao.getDnt(organIds,new Date());
		
		
		
		if(dnt != null)
		{
			dnt.set(DailyNursingTotal.column_zr,dnt.getDouble(DailyNursingTotal.column_zr)+(double)price);
			if (!dnt.update()) {
				log.debug("更新日综合查询表失败");
				throw new RuntimeException("更新日综合查询表失败!");
			}
		}
		else
		{	
			
			DailyNursingTotal  dntNew = new DailyNursingTotal();
			dntNew.set(DailyNursingTotal.column_organids, organIds)
				  .set(DailyNursingTotal.column_date, ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd));
			dntNew.set(DailyNursingTotal.column_zr,(double)price);
			if (!dntNew.save()) {
				log.debug("更新日综合查询表失败");
				throw new RuntimeException("更新日综合查询表失败!");
			}
		}
		return  ConstantRender.render_success_code;
	}

}
